<?php

namespace Common\Controller;
namespace Common\Controller;

use Think\Controller;
use Org\Ripcord\ripcord;

/*
参考文档：
http://www.odoo.com/documentation/8.0/api_integration.html
bug ：分页有问题
*/
class OdooApiController extends Controller {
    public $url;
    public $db;
    public $username;
    public $password;
    public $models;
    public $common;
    function __construct() {
        self::_initialize ();
    }
    function _initialize() {
         
		 
		 $this->url ='http://erp.newbeemall.com';
         $this->db = 'anxe_021';
         $this->username ="admin";
         $this->password ="oscg2015";
        // echo $this->db;
 
        $this->common = Ripcord::client ( $this->url."/xmlrpc/2/common" );

        // Logging in
		if(!isset($_SESSION['LOGIN_UID'])||!is_numeric($_SESSION['LOGIN_UID']))
		{
			$uid = $this->common->authenticate ($this->db,$this->username, $this->password, array () );
			//$this->common->version();
			$_SESSION['LOGIN_UID']=$uid;
			//echo "login fisrst<br>";
		}
        
        //echo "123";
		//var_dump($_SESSION['LOGIN_UID']);
        define(UID,$_SESSION['LOGIN_UID']);
        //echo "222===============uid=".$uid."<br>";
        $this->models = Ripcord::client( $this->url."/xmlrpc/2/object");
		return $uid;
		
    }
	 function _initializeB() {
		 $this->url ='http://erp.newbeemall.com:6002';
         $this->db = 'cuntan_new';
         $this->username ="admin";
         $this->password ="admin";
        // echo $this->db;
        $this->common = Ripcord::client ( $this->url."/xmlrpc/2/common" );
        // Logging in
		if(!isset($_SESSION['LOGIN_UID'])||!is_numeric($_SESSION['LOGIN_UID']))
		{
			$uid = $this->common->authenticate ($this->db,$this->username, $this->password, array () );
			$_SESSION['LOGIN_UID']=$uid;
		}
        
        //echo "123";
		//var_dump($_SESSION['LOGIN_UID']);
        define(UID,$_SESSION['LOGIN_UID']);
        $this->models = Ripcord::client( $this->url."/xmlrpc/2/object");
		return $uid;
		
    }

		 function _initializePos() {
         
		 
		 $this->url ='http://pos.newbeemall.com';
         $this->db = 'pos';
         $this->username ="admin";
         $this->password ="admin";
        // echo $this->db;
 
        $this->common = Ripcord::client ( $this->url."/xmlrpc/2/common" );

        // Logging in
		if(!isset($_SESSION['POSLOGIN_UID'])||!is_numeric($_SESSION['POSLOGIN_UID']))
		{
			$uid = $this->common->authenticate ($this->db,$this->username, $this->password, array () );
			$_SESSION['LOGIN_UID']=$uid;
			echo "login fisrst<br>";
		}
        
        //echo "123";
		//var_dump($_SESSION['LOGIN_UID']);
        define(UID,$_SESSION['POSLOGIN_UID']);
        echo "222===============uid=".$uid."<br>";
        $this->models = Ripcord::client( $this->url."/xmlrpc/2/object");
		return $uid;
		
    }
	
	 function _initializeH() {
         
		 
		 $this->url ='http://222.180.250.72:6001';
         $this->db = 'H_WMS';
         $this->username ="admin";
         $this->password ="oscg2015";
        // echo $this->db;
 
        $this->common = Ripcord::client ( $this->url."/xmlrpc/2/common" );

        // Logging in
		if(!isset($_SESSION['LOGIN_UID'])||!is_numeric($_SESSION['LOGIN_UID']))
		{
			$uid = $this->common->authenticate ($this->db,$this->username, $this->password, array () );
			$_SESSION['LOGIN_UID']=$uid;
			//echo "login fisrst<br>";
		}
        
        //echo "123";
		//var_dump($_SESSION['LOGIN_UID']);
        define(UID,$_SESSION['LOGIN_UID']);
        //echo "222===============uid=".$uid."<br>";
        $this->models = Ripcord::client( $this->url."/xmlrpc/2/object");
		return $uid;
    }

		 
    /**
     * 获取版本
     */
    public function version() {
        $data = $common->version ();
        dump ( $common );
        dump ( $data );
    }
	
	public function getposorderids()
    {
		
		$ids = self::execute_kw ( 'pos.order', 'search', array (
                array (
                        array (
                                'state',
                                '=',
                                'paid' 
                        )
                ) 
        ), array (
                'offset' => 0,
                'limit' => 999 
        ) );
        return $ids;
	}	
	public function autopick($ids)
	{
		 $rec= self::execute_kw ( 'stock.picking', 'search',array (
                array (
                        array (
                                'state',
                                '=',
                                'confirmed' 
                        ),
                )  )
				);
		 $total=count($rec);
		 $records=array_slice($rec,0,3);
		 
		 $recordsx = self::execute_kw ( 'stock.picking', 'action_assign',array($records) );
		 
		  
		 return $total-count($records);
		
	}
	public function test_inventory()
	{
		echo "hello";
		$ids=94;
		$recordsx = self::execute_kw('stock.inventory', 'read',array($ids) );
		$recordsx=self::execute_kw('stock.inventory', '_get_inventory_lines',$recordsx );
		
		
		var_dump($recordsx);
		
	}
	///自动播种
	public function autobozhong()
	{
		 $rec= self::execute_kw ( 'stock.picking', 'search',array (
                array (
                        array (
                                'picking_type_id',
                                '=',
                                7 
                        ), array (
                                'state',
                                '=',
                                'assigned' 
                        ),
                )  )
				);
			
		$total=count($rec);
		$records=array_slice($rec,0,1); 
		$recordsx = self::execute_kw ( 'stock.picking', 'do_transfer',array($records) );
		return $total-count($records);
	}
	public function getposorderinfo($ids)
	{
		 
		 
		 $records = self::execute_kw ( 'pos.order', 'read', array (
                $ids 
        ) );
		return $records;
		
	}
	
	public function getposorderlines($ids)
	{
		 
		 
		 $records = self::execute_kw ( 'pos.order.line', 'read', array (
                $ids 
        ) );
		return $records;
		
	}
	
	public function getposorderpays($ids)
	{
		 
		 
		 $records = self::execute_kw ( 'account.bank.statement.line', 'read', array (
                $ids 
        ) );
		return $records;
		
	}
	
	public function getstock($sku)
	{
		$limit =1;
		$t1=time()+microtime();
        $data = self::execute_kw ('product.template', 'search_read', array (
                array (
                       array('default_code','ilike',$sku),
                       //array('qty_available','>',0),
                    
                ) 
        ),array('limit' => $limit)  
        );
		$t=time()+microtime()-$t1;
		echo $t."<br/>";
		return $data[0]['qty_available'];
		
	}
	
	
    /**
     * 检测权限
     */
    public function check_access_rights() {
        // 检测对象是否有权限

        $data = self::execute_kw ( 'res.partner', 'check_access_rights', array (
                'read' 
        ), array (
                'raise_exception' => false 
        ) );

        dump ( $data );
    }
    public function search() {
        // List records
        $data = self::execute_kw ( 'res.partner', 'search', array (
                array (
                        array (
                                'is_company',
                                '=',
                                true 
                        ),
                        array (
                                'customer',
                                '=',
                                true 
                        ) 
                ) 
        ) );
        dump ( $data );
    }
	public function readbySku($sku)
	{
		 
		 $limit =1;
        $data = self::execute_kw ('product.template', 'search_read', array (
                array (
                       array('default_code','ilike',$sku),
                       //array('qty_available','>',0),
                    
                ) 
        ),array('limit' => $limit)  
        );
        
        return $data;
		
		
	}
	public function getallskockB($page)
	{

		$limit=5;
		
        $ids = self::execute_kw ('product.template', 'search', array (
                array (
                   array ('qty_available','>',1000 )     
                ) 
        ));
		
		$data=self::execute_kw('product.template', 'read',array($ids),array('fields'=>array('id', 'list_price')));

		$t=time()+microtime()-$t1;
		echo $t."<br/>";
		return $data;

	}
	public function getallsku($indata)
	{
 
		
		
		
	}	
	public function readbySo($poid='PO00421',$limit=5){
		self::_initialize ();
		 // Search and read
        $data = self::execute_kw ('purchase.order', 'search_read', array (
                array (
                       array('name','ilike',$poid)
                    
                ) 
        ),array('limit' => $limit)  
        );
        ///var_dump( $data);
		//var_dump($data[0]['order_line']);
		
		$dataline = self::execute_kw ('purchase.order.line', 'read', array (
             $data[0]['order_line'] 
        ))  ; 
		
		return $dataline;
		
	}
	public function getskubeianids()
	{
		
		$limit=9999;
        $data=	self::execute_kw ('sku.info', 'search_count', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft')
                    
                ) 
        ),  array('offset'=>10,'limit' => $limit)
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
		
	}
	
	public function readskubeian($ids)
	{
		$data = self::execute_kw ( 'sku.info', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
	}
	////读取订单ids from erp
	public function getorderids()
	{
		$limit=9999;
        $data=	self::execute_kw ('channel.order', 'search', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft')
                    
                ) 
        ),array('limit' => $limit)  
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
		
	}
	
	public function readorder($ids)
	{
		$data = self::execute_kw ( 'channel.order', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
		
	}
	
	public function readorderline($ids)
	{
		$data = self::execute_kw ( 'channel.order.line', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
		
	}
	
	////读取B仓的分拣单
	public function getpickingids()
	{
		
		$limit=9999;
        $data=	self::execute_kw ('stock.picking', 'search', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft')
                    
                ) 
        ),array('limit' => $limit)  
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
		
	}
	
	////读取B仓的分拣单/仅获取打包单
	public function getpickingids2()
	{
		
		$limit=9999;
        $data=	self::execute_kw ('stock.picking', 'search', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft'),array('picking_type_id','=',9),array('ship_no','!=','')
                ) 
        ),array('limit' => $limit)  
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
		
	}
	
	public function readstockpicking($ids)
	{
		$data = self::execute_kw ( 'stock.picking', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
		
	}
	
		public function readstockmovelines($ids)
	{
		$data = self::execute_kw ( 'stock.move', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
		
	}
	////进境清单列表
	public function getjjqdlist()
	{
		 self::_initialize();
		$limit=9999;
        $data=	self::execute_kw ('trans.order', 'search', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft')
                    
                ) 
        ),array('limit' => $limit)  
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
		
	}
	
	/////获取进境清单内容
	public function readtransorder($ids)
	{
		$data = self::execute_kw ( 'trans.order', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
	}
	///获取jjqd lines
	public function readjjqdlines($ids)
	{
		
		self::_initialize();
		$data = self::execute_kw ( 'trans.order.lines', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
	}
	///
	public function getpancunids()
	{
		self::_initializeB();
		$limit=9999;
        $data=	self::execute_kw ('stock.inventory', 'search', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft')
                    
                ) 
        ),array('limit' => $limit)  
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
	}
	public function readpancun($ids)
	{
		self::_initializeB();
		$data = self::execute_kw ('stock.inventory', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
	}
	////采购单列表
	public function readallpurchaseids()
	{   ////取消的订单和未确认的订单23
	    self::_initialize();
		$limit=9999;
        $data=	self::execute_kw ('purchase.order', 'search', array (
                array (
                       array('state','!=','cancel'),array('state','!=','draft'),array('state','!=','wait')
                    
                ) 
        ),array('limit' => $limit)  
        );	
		if($data['faultCode']==1) echo "false";
		return $data;
	}
	////获取IDS的采购单
	public function readpurchase($ids)
	{
		self::_initialize();
		$data = self::execute_kw ( 'purchase.order', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
		
	}
	///获取ids的采购单lines
	public function readpurchlines($ids)
	{
		
		self::_initialize();
		$data = self::execute_kw ( 'purchase.order.line', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'state',
                        'description' 
                ) 
        ) );
		
		return $data;
	}
    public function search_page() {
        // Pagination
        $data = self::execute_kw ( 'res.partner', 'search', array (
                array (
                        array (
                                'is_company',
                                '=',
                                true 
                        ),
                        array (
                                'customer',
                                '=',
                                true 
                        ) 
                ) 
        ), array (
                'offset' => 10,
                'limit' => 5 
        ) );
        dump ( $data );
    }
    public function search_count() {
        // Count records
        $data = self::execute_kw ( 'res.partner', 'search_count', array (
                array (
                        array (
                                'is_company',
                                '=',
                                true 
                        ),
                        array (
                                'customer',
                                '=',
                                true 
                        ) 
                ) 
        ) );
        dump ( $data );
    }
    public function read_records() {
        // Read records
        $ids = self::execute_kw ( 'res.partner', 'search', array (
                array (
                        array (
                                'is_company',
                                '=',
                                true 
                        ),
                        array (
                                'customer',
                                '=',
                                true 
                        ) 
                ) 
        ), array (
                'limit' => 1 
        ) );
        $records = self::execute_kw ( 'res.partner', 'read', array (
                $ids 
        ) );
        // count the number of fields fetched by default
        $data = count ( $records [0] );

        dump ( $data );
    }
    public function read_field() {
        // 只显示需要的字段
        $data = self::execute_kw ( 'res.partner', 'read', array (
                $ids 
        ), array (
                'fields' => array (
                        'name',
                        'country_id',
                        'comment' 
                ) 
        ) );
        dump ( $data );
    }
    public function record_attr() {
        // Listing record fields
        $data = self::execute_kw ( 'res.partner', 'fields_get', array (), array (
                'attributes' => array (
                        'string',
                        'help',
                        'type' 
                ) 
        ) );
        dump ( $data );
    }
    public function search_read() {

        // Search and read
        $data = self::execute_kw ( 'res.partner', 'search_read', array (
                array (
                        array (
                                'is_company',
                                '=',
                                true 
                        ),
                        array (
                                'customer',
                                '=',
                                true 
                        ) 
                ) 
        ), array (
                'fields' => array (
                        'name',
                        'country_id',
                        'comment' 
                ),
                'limit' => 5 
        ) );
        dump ( $data );
    }
    public function create() {
        // Create records
        $id = self::execute_kw ( 'res.partner', 'create', array (
                array (
                        'name' => "New Partner" 
                ) 
        ) );
        dump ( $id );
    }
    /**
     * 更新记录
     * 
     * @param unknown $id            
     */
    public function update($id) {
        // Update records
        self::execute_kw ( 'res.partner', 'write', array (
                array (
                        $id 
                ),
                array (
                        'name' => "Newer partner" 
                ) 
        ) );
    }
    public function name_get($id) {
        // get record name after having changed it
        $data = self::execute_kw ( 'res.partner', 'name_get', array (
                array (
                        $id 
                ) 
        ) );

        dump ( $data );
    }
    public function delete($id) {
        // Delete records
        self::execute_kw ( 'res.partner', 'unlink', array (
                array (
                        $id 
                ) 
        ) );
        // check if the deleted record is still in the database
        $data = self::execute_kw ( 'res.partner', 'search', array (
                array (
                        array (
                                'id',
                                '=',
                                $id 
                        ) 
                ) 
        ) );

        dump ( $data );
    }
    /**
     * Available reports can be listed by searching the ir.actions.report.xml model, fields of interest being
     * model
     * the model on which the report applies, can be used to look for available reports on a specific model
     * name
     * human-readable report name
     * report_name
     * the technical name of the report, used to print it
     * Reports can be printed over RPC with the following information:
     * the name of the report (report_name)
     * the ids of the records to include in the report
     */
    public function report() {
        header ( "Pragma: public" ); // required
        header ( "Expires: 0" );
        header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
        header ( "Cache-Control: private", false ); // required for certain browsers
        header ( "Content-Type: application/pdf" );
        // header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
        header ( "Content-Transfer-Encoding: binary" );
        // header("Content-Length: ".$fsize);
        // Report printing
        $invoice_ids = self::execute_kw ( 'account.invoice', 'search', array (
                array (
                        array (
                                'type',
                                '=',
                                'out_invoice' 
                        ),
                        array (
                                'state',
                                '=',
                                'open' 
                        ) 
                ) 
        ) );
        $report = ripcord::client ( "$this->url/xmlrpc/2/report" );
        $result = $report->render_report ( $this->db, UID, $this->password, 'account.report_invoice', $invoice_ids );
        $report_data = base64_decode ( $result ['result'] );

        echo $report_data;
    }

    /**
     * While we previously used fields_get() to query a model’s and have been using an arbitrary model from the start, Odoo stores most model metadata inside a few meta-models which allow both querying the system and altering models and fields (with some limitations) on the fly over XML-RPC.
     * ir.model
     *
     * Provides informations about Odoo models themselves via its various fields
     * name
     * a human-readable description of the model
     * model
     * the name of each model in the system
     * state
     * whether the model was generated in Python code (base) or by creating an ir.model record (manual)
     * field_id
     * list of the model’s fields through a One2many to ir.model.fields
     * view_ids
     * One2many to the Views defined for the model
     * access_ids
     * One2many relation to the Access Control set on the model
     * ir.model can be used to
     * query the system for installed models (as a precondition to operations on the model or to explore the system’s content)
     * get information about a specific model (generally by listing the fields associated with it)
     * create new models dynamically over RPC
     * Warning
     * “custom” model names must start with x_
     * the state must be provided and manual, otherwise the model will not be loaded
     * it is not possible to add new methods to a custom model, only fields
     */
    public function inspection() {
        // Inspection and introspection
        self::execute_kw ( 'ir.model', 'create', array (
                array (
                        'name' => "Custom Model",
                        'model' => 'x_custom_model',
                        'state' => 'manual' 
                ) 
        ) );
        $data = self::execute_kw ( 'x_custom_model', 'fields_get', array (), array (
                'attributes' => array (
                        'string',
                        'help',
                        'type' 
                ) 
        ) );
        dump ( $data );
    }
    /**
     * ir.model.fields
     *
     * Provides informations about the fields of Odoo models and allows adding custom fields without using Python code
     * model_id
     * Many2one to ir.model to which the field belongs
     * name
     * the field’s technical name (used in read or write)
     * field_description
     * the field’s user-readable label (e.g. string in fields_get)
     * ttype
     * the type of field to create
     * state
     * whether the field was created via Python code (base) or via ir.model.fields (manual)
     * required, readonly, translate
     * enables the corresponding flag on the field
     * groups
     * field-level access control, a Many2many to res.groups
     * selection, size, on_delete, relation, relation_field, domain
     * type-specific properties and customizations, see the fields documentation for details
     * Like custom models, only new fields created with state="manual" are activated as actual fields on the model.
     * computed fields can not be added via ir.model.fields, some field meta-information (defaults, onchange) can not be set either
     */
    public function custom_model() {
        //
        $id = self::execute_kw ( 'ir.model', 'create', array (
                array (
                        'name' => "Custom Model",
                        'model' => 'x_custom',
                        'state' => 'manual' 
                ) 
        ) );
        self::execute_kw ( 'ir.model.fields', 'create', array (
                array (
                        'model_id' => $id,
                        'name' => 'x_name',
                        'ttype' => 'char',
                        'state' => 'manual',
                        'required' => true 
                ) 
        ) );
        $record_id = self::execute_kw ( 'x_custom', 'create', array (
                array (
                        'x_name' => "test record" 
                ) 
        ) );
        $data = self::execute_kw ( 'x_custom', 'read', array (
                array (
                        $record_id 
                ) 
        ) );
        dump ( $data );
    }
    /**
     * Workflows can be moved along by sending them signals.
     * Instead of using the top-level execute_kw,
     * signals are sent using exec_workflow.Signals are sent to a specific record,
     * and possibly trigger a transition on the workflow instance associated with the record.
     */
    public function workflow() {
        // Workflow manipulations
        $client = self::execute_kw ( 'res.partner', 'search_read', array (
                array (
                        array (
                                'customer',
                                '=',
                                true 
                        ) 
                ) 
        ), array (
                'limit' => 1,
                'fields' => array (
                        'property_account_receivable',
                        'property_payment_term',
                        'property_account_position' 
                ) 
        ) );
		$client=$client[0];
        $invoice_id = self::execute_kw ( 'account.invoice', 'create', array (
                array (
                        'partner_id' => $client ['id'],
                        'account_id' => $client ['property_account_receivable'] [0],
                        'invoice_line' => array (
                                array (
                                        0,
                                        false,
                                        array (
                                                'name' => "AAA" 
                                        ) 
                                ) 
                        ) 
                ) 
        ) );

        $this->models->exec_workflow ( $this->db, $this->uid, $this->password, 'account.invoice', 'invoice_open', $invoice_id );
    }
    public function index() {
        dump ( $this );
    }
    public function execute_kw($objName, $cmd, $args) {
		//echo $this->db;
        $data = $this->models->execute_kw( $this->db, UID, $this->password, $objName, $cmd, $args );
        return $data;
    }
}